package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjzuji.rental.Bean.ApiDetailRequest;
import com.cjzuji.rental.Bean.ApiQueryRequest;
import com.cjzuji.rental.Bean.ApiResponse;
import com.cjzuji.rental.Bean.OrderData;
import com.cjzuji.rental.dao.OrderBillDao;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderContractMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.mapper.OrderUserMapper;
import com.cjzuji.rental.pojo.*;
import com.cjzuji.rental.service.OrderService;
import com.cjzuji.rental.util.OrdersUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderBillDao orderBillDao;
    @Autowired
    OrderUserMapper orderUserMapper;
    @Autowired
    OrderContractMapper orderContractMapper;
    @Autowired
    OrderBillMapper orderBillMapper;
    @Value("${excel.export.temp.dir:/temp/exports}")
    private String exportTempDir;
    // 分页大小
    private static final int PAGE_SIZE = 2000;

    // 内存中保留的行数
    private static final int ROW_ACCESS_WINDOW_SIZE = 100;

    @Override
    public void processOrders(List<OrderData> orders) {
        for (OrderData order : orders) {
            Map<String, String> allData = (Map<String, String>) order.getAllData();
            log.info("处理订单数据: {}", allData);
        }
    }

    // 下载exl文件
    public File downLoadFile(List<OrdersDetailDTO> dataList, String outputPath) {

        // 参数校验
        if (dataList == null) {
            throw new IllegalArgumentException("订单数据列表不能为null");
        }
        if (StringUtils.isEmpty(outputPath)) {
            throw new IllegalArgumentException("输出路径不能为空");
        }
        try {
            // 确保输出目录存在
            File outputDir = OrdersUtil.writeExcelToLocal(dataList, outputPath);
            if (!outputDir.exists() && !outputDir.mkdirs()) {
                throw new IOException("无法创建输出目录: " + outputDir.getAbsolutePath());
            }

            return OrdersUtil.writeExcelToLocal(dataList, outputPath);
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败: " + e.getMessage(), e);
        }
    }

//    public File getOrdersFile(String userName) {
//        List<OrdersDetailDTO> row = orderMapper.selectOrderPage(userName);
//        String outputPath = "youping" + System.currentTimeMillis() + ".xlsx";
//        row.forEach(item -> {
//            System.out.println("id~~~~~~~~~~~~"+item.getId());
//            // 查询订单用户信息
//            List<OrderBill> userInfo = orderBillDao.getOrderBillList(item.getId());
//            System.out.println("List~~~~~~~~~~~~"+userInfo.size());
//            item.setOrderBillList(userInfo);
//        });
//        // 3. 生成新的Excel文件并保存到本地
//        File outputFile = downLoadFile(row, outputPath);
//        return outputFile;
//    }

    public File getOrdersFile(String userName) {
        // 1. 分页查询订单数据
        Page<Orders> page = new Page<>(8, PAGE_SIZE);
        IPage<OrdersDetailDTO> pageData = orderMapper.selectOrderPage(page);
        List<OrdersDetailDTO> row = pageData.getRecords();
        // 2. 遍历订单数据，查询并设置账单信息
        row.forEach(item -> {
            System.out.println("id~~~~~~~~~~~~" + item.getId());
            // 查询订单用户信息
            List<OrderBill> userInfo = orderBillDao.getOrderBillList(item.getId());
            //System.out.println("List~~~~~~~~~~~~" + userInfo.size());
            item.setOrderBillList(userInfo);
        });
        // 3. 生成新的Excel文件并保存到本地
        String outputPath = "youping" + System.currentTimeMillis() + ".xlsx";
        File outputFile = downLoadFile(row, outputPath);
        return outputFile;
    }

    @Override
    public Object getOrderList(ApiQueryRequest condition,int pageIndex, int pageSize) {
        // 创建分页对象
        Page page = new Page(pageIndex,pageSize);
        // mybatis plus查询
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        //模糊查询
        if(StringUtils.hasText(condition.getOrderId())){
            queryWrapper.like("order_id",condition.getOrderId());
        }
        if(StringUtils.hasText(condition.getUserPhone())){
            queryWrapper.like("phone",condition.getUserPhone());
        }
        if(StringUtils.hasText(condition.getUserName())){
            queryWrapper.like("real_name",condition.getUserName());
        }
        //精确查询
        if(condition.getShop() != 0){
            queryWrapper.eq("shop_id",condition.getShop());
        }
        if(condition.getPlatform() != 0){
            queryWrapper.eq("platform_id",condition.getPlatform());
        }
        if(condition.getOrderStatus() != 0){
            queryWrapper.eq("status",condition.getOrderStatus());
        }
        if(StringUtils.hasText(condition.getAssigner())){
            queryWrapper.eq("assigner",condition.getAssigner());
        }
        // selectPage是内部的方法，返回值是Page<T>
        Page<Orders> pageResult = orderMapper.selectPage(page, queryWrapper);
        return pageResult;
    }

    @Override
    public ApiDetailRequest getOrderDetail(Long orderId) {
        //查询是否存在ID
        Orders orders = orderMapper.selectById(orderId);
        if (orders == null) {
            throw new RuntimeException("订单不存在"+orderId);
        }
        ApiDetailRequest detailRequest = new ApiDetailRequest();
        detailRequest.setOrderId(orders.getId());
        //查询用户信息
        QueryWrapper<OrderUser> userWrapper = new QueryWrapper<>();
        userWrapper.eq("order_id",orderId);
        OrderUser userInfo = orderUserMapper.selectOne(userWrapper);
        detailRequest.setUserInfo(userInfo);
        //查询合同信息
        QueryWrapper<OrderContract> contractWrapper = new QueryWrapper<>();
        contractWrapper.eq("order_id",orderId);
        List<OrderContract> contractInfo = orderContractMapper.selectList(contractWrapper);
        detailRequest.setContractInfo(contractInfo);
        //查询账单信息
        QueryWrapper<OrderBill> billWrapper = new QueryWrapper<>();
        billWrapper.eq("order_id",orderId);
        List<OrderBill> billInfo = orderBillMapper.selectList(billWrapper);
        detailRequest.setBillInfo(billInfo);
        return detailRequest;
    }
}